package com.oddfar.campus.business.controller.web;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.oddfar.campus.common.domain.entity.AIResponseAns;
import com.oddfar.campus.common.domain.entity.AIResponseEntity;
import com.oddfar.campus.common.domain.entity.Question;
import com.oddfar.campus.common.properties.AIProperties;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * AI聊天接口
 * @author xianziye
 */
@RestController
@RequestMapping
public class UserAskAIController {

    @Autowired
    private AIProperties aiProperties;

    /**
     * 实现ai聊天接口
     * @param question
     * @return
     */
    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("/askAI")
    public AIResponseAns getAIResponse(@org.springframework.web.bind.annotation.RequestBody Question question) {

//        OkHttpClient client = new OkHttpClient();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(60, TimeUnit.SECONDS) // 读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS) // 写入超时时间
                .build();

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "gpt-3.5-turbo");

        JSONArray messages = new JSONArray();
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant");
        messages.put(systemMessage);

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user"); // 角色
        userMessage.put("content", question.getQuestion()); // 用户提问信息
        messages.put(userMessage);

        requestBody.put("messages", messages);

        RequestBody body = RequestBody.create(requestBody.toString(), MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(aiProperties.getUri())
                .addHeader("Authorization", aiProperties.getApiKey())
                .post(body)
                .build();

        AIResponseAns aiResponseAns = null;

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            String responseBody = response.body().string();

            AIResponseEntity chatCompletion = JSON.parseObject(responseBody, AIResponseEntity.class);

            aiResponseAns = new AIResponseAns();
            aiResponseAns.setAnswer(chatCompletion.getChoices().get(0).getMessage().getContent());
            // 返回信息
            return aiResponseAns;

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("-------------------------AI异常-------------------------");
            aiResponseAns.setAnswer("网络不佳，请重试！");
            return aiResponseAns;
        }
    }
}
